package com.jinzhi.sms.controller;

import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.ExaminationBatchDO;
import com.jinzhi.jzweb.domain.MessageplatfromDO;
import com.jinzhi.jzweb.service.ExaminationBatchService;
import com.jinzhi.jzweb.service.MessageplatfromService;
import com.jinzhi.jzweb.utils.FileUtil;
import com.jinzhi.sms.support.SmsManager;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 *
 * </pre>
 * <small> 2018/8/30 19:17 | Aron</small>
 */
@RestController
@RequestMapping("/api/sms")
public class SmsController {

    @Autowired
    private SmsManager smsService;
    @Autowired
    private ExaminationBatchService examinationBatchService;
    @Autowired
    private MessageplatfromService messageplatfromService;

    @GetMapping("/sendCode")
    @Log("发送验证码")
    @ApiOperation("发送验证码")
    public Result sendCode(String prefix, String mobile) {
        Object smsDemo = EhCacheUtil.get("登录短信验证");
        if(smsDemo == null){
            MessageplatfromDO messageplatfromDO = messageplatfromService.findOneByKv("登录短信验证");
            if(messageplatfromDO != null){
                EhCacheUtil.put("登录短信验证",messageplatfromDO.getSmsDemo());
                smsService.send(prefix, mobile,messageplatfromDO.getSmsDemo());
            }else{
                return Result.fail("短信模板错误，请联系管理员！");
            }
        }else{
            smsService.send(prefix, mobile,(String) smsDemo);
        }

        return Result.ok("发送成功");
    }

    @GetMapping("/sendSms")
    @Log("发送短信")
    @ApiOperation("发送短信")
    @RequiresAuthentication
    public Result sendSms(String mobile,String templateCode) {
        Map map = new HashMap();
        map.put("msg","测试服务");
        smsService.send(mobile, templateCode, map);
        return Result.ok("发送成功");
    }

    @GetMapping("/verifyCode")
    @Log("校验验证码")
    @ApiOperation("校验验证码")
    public Result verifyCode(String prefix, String mobile, String code) {
        smsService.verify(prefix, mobile, code);
        return Result.ok("校验成功");
    }

    @GetMapping("/delFile")
    @Log("删除文件")
    @ApiOperation("删除文件")
    public Result delFile(String filePath) {
        FileUtil.delFile(filePath);
        return Result.ok("删除成功");
    }

    @GetMapping("/selRand")
    @Log("测试")
    @ApiOperation("测试")
    public Result selRand() {
        List<ExaminationBatchDO> examinationBatchDOS = examinationBatchService.findByKv();
        return Result.ok(examinationBatchDOS);
    }


}
